<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/12/31 0031
 * Time: 14:58
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace app\common\business;

use app\common\model\MallManager as ModelObj;
use app\common\validate\Manager as ValObj;
use think\Exception;

class Manager extends Base
{
    /**
     * @var \app\common\validate\Manager
     */
    protected ValObj $valObj;
    /**
     * @var \app\common\model\MallManager
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * @param array $data
     * @param string $scene
     * @throws Exception
     */
    protected function isValidateAdd(array $data = [], string $scene = 'add')
    {
        if (!$this->valObj->check($data)) {
            throw new Exception($this->valObj->getError());
        }
    }


    /**
     * 获取指定商家信息
     * @param array $where
     * @param string $field
     * @return array|\think\Model|null
     * @throws Exception
     */
    public function  getManagerInfo(array $where,string $field){

        try {
            $result = $this->modelObj->getModelByInfo($where,$field);

        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }

        return $result;
    }

    /**
     * 编辑商家信息
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function saveData($data){
        //验证字段
        $this->isValidateAdd($data);
        try{
            $info =$this->modelObj->getModelByInfo([['openid','=',$data['openid']]],'*');
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
        if($info){
            $info->save($data);
        }else{
            $minfo=$this->modelObj->where("openid='".$data['openid']."'")->find();
            if(!$minfo){
                $this->modelObj->save($data);
            }else{
                throw new Exception("您已经入驻成为商家了哦");
            }

        }
        return true;
    }

}